<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-card>
      <el-form :inline="true" :model="listQuery" size="small">
        <el-form-item>
          <el-input
            placeholder="投票题目"
            clearable
            v-model="listQuery.name"
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click.native="handleFilter"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >
            新增投票
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="handleBatchDelete"
          >
            批量删除
          </el-button>
        </el-form-item>
      </el-form>

      <!-- table列表 -->
      <el-table
        style="width: 100%"
        border
        stripe
        size="small"
        :data="datas"
        v-loading="listLoading"
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column label="#" align="center" type="selection" />
        <el-table-column type="expand" align="center">
          <template slot-scope="scope">
            <el-table
              :data="scope.row.choices"
              border
              v-if="scope.row.choices.length > 0"
              size="mini"
              fit
              highlight-current-row
              style="width: 80%"
            >
              <el-table-column align="center" label="序号" type="index" />
              <el-table-column align="left" label="选项名称" prop="name" />
              <el-table-column
                align="center"
                label="投票数量"
                prop="vote_nums"
                width="200px"
              />
              <el-table-column align="center" label="操作" width="200px">
                <template slot-scope="scope">
                  <el-button
                    type="warning"
                    size="mini"
                    icon="el-icon-upload"
                    @click="handleUpload(scope.row)"
                    >图片</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column
          v-for="column in tableColumns"
          :key="column.key"
          :label="column.title"
          :prop="column.key"
          :align="column.align ? column.align : 'center'"
          :width="column.width ? column.width : ''"
        >
        </el-table-column>
        <el-table-column align="center" label="操作" width="200px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="handleEdit(scope)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="handleDelete(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getQuestionList"
      />
    </el-card>
    <!-- 弹框 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="getTitle"
      width="800px"
      top="10px"
      :close-on-click-modal="false"
    >
      <el-row style="margin-bottom: 10px; margin-top: -30px">
        <el-col :span="12" :offset="1">
          <el-button-group>
            <el-button
              type="primary"
              size="small"
              plain
              @click="handleSave(false)"
              >保存</el-button
            >
            <el-button
              type="primary"
              size="small"
              plain
              @click="handleSave(true)"
              >保存并新增</el-button
            >
            <el-button
              type="danger"
              size="small"
              plain
              @click="dialogVisible = false"
              >关闭</el-button
            >
          </el-button-group>
        </el-col>
      </el-row>
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="100px"
        label-position="right"
        style="padding: 0 20px"
        status-icon
        size="mini"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="投票题目" prop="name">
              <el-input
                type="text"
                v-model="form.name"
                placeholder="投票题目"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="开始日期" prop="begin_date">
              <el-date-picker
                v-model="form.begin_date"
                type="date"
                placeholder="开始日期"
                clearable
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="end_date">
              <el-date-picker
                v-model="form.end_date"
                type="date"
                placeholder="结束日期"
                clearable
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="最大数量" prop="max_num">
              <el-input
                type="number"
                v-model="form.max_num"
                placeholder="最大数量"
                clearable
              />        
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="flag">
              <el-select v-model="form.flag" placeholder="状态">
                <el-option
                  v-for="item in flags"
                  :key="item.vallue"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="类型" prop="category">
              <el-select v-model="form.category" placeholder="类型">
                <el-option
                  v-for="item in cates"
                  :key="item.vallue"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="投票说明" prop="desc">
              <el-input
                type="text"
                v-model="form.desc"
                placeholder="投票说明"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <div class="bottom">
          <el-tabs v-model="activeName">
            <el-tab-pane label="投票选项" name="first">
              <el-row>
                <el-col :span="12">
                  <el-button-group>
                    <el-button
                      type="primary"
                      plain
                      size="small"
                      @click="addItem"
                      >新增行</el-button
                    >
                    <el-button
                      plain
                      type="primary"
                      size="small"
                      @click="deleteItem"
                      >删除</el-button
                    >
                  </el-button-group>
                </el-col>
              </el-row>
              <el-table
                :data="form.choices"
                border
                highlight-current-row
                style="width: 100%"
                size="mini"
                id="detail"
                @selection-change="handleItemChange"
              >
                <el-table-column type="selection" width="40"></el-table-column>

                <el-table-column label="选项" align="center">
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'choices.' + scope.$index + '.name'"
                      label-width="0"
                      :rules="formRules.choice_name"
                    >
                      <el-input
                        v-model="scope.row.name"
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="投票数量" align="center" width="200">
                  <template slot-scope="scope">
                    <el-form-item
                      label-width="0"
                      :prop="'choices.' + scope.$index + '.vote_nums'"
                    >
                      <el-input
                        v-model="scope.row.vote_nums"
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-form>
    </el-dialog>
    <!-- 图片上传 -->
    <el-dialog
      :visible.sync="dlgUploadVisible"
      title="商家图片"
      width="800px"
      destroy-on-close
      @close="handleClose"
    >
      <el-form
        label-width="100px"
        :model="uploadForm"
        label-position="right"
        style="width: 95%; padding: 0 30px"
        status-icon
      >
        <el-form-item label="选项名称">
          <el-input
            v-model="uploadForm.choice_name"
            size="small"
            disabled
          ></el-input>
        </el-form-item>

        <el-form-item label="选项图片">
          <el-upload
            ref="upload"
            name="image"
            action="/api/polls/image_upload/"
            multiple
            :on-preview="handlePreview"
            :before-upload="handleBeforeUpload"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :file-list="fileList"
            accept=".jpg, .jpeg, .png, .gif, .JPG, .JPEG, .PNG, .GIF"
            :headers="headerObj"
            :data="uploadData"
            list-type="picture-card"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dlgUploadVisible = false" size="mini"
          >关闭</el-button
        >
      </div>
      <el-dialog :visible.sync="dlgImageVisible" append-to-body>
        <el-image
          style="width: 100%; min-height: 400px"
          :src="dlgImageUrl"
          fit="fill"
        ></el-image>
        <div slot="footer">
          <el-button @click="dlgImageVisible = false" size="mini"
            >关闭</el-button
          >
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import Pagination from "@/components/Pagination";
import { pickerOptions } from "@/utils/const";
import {
  getQuestions,
  addQuestion,
  updateQuestion,
  delQuestion,
  delQuestions,
  delChoices,
  delChoiceImage,
} from "@/api/polls";

const defChoiceItem = {
  name: null,
  vote_nums: 0,
};

const defaultForm = {
  id: null,
  name: null,
  desc: null,
  begin_date: null,
  end_date: null,
  flag: 1,
  choices: [],
};

export default {
  name: "Question",
  data() {
    return {
      form: Object.assign({}, defaultForm),
      activeName: "first",
      formRules: {
        name: [{ required: true, message: "请输入投票题目", trigger: "blur" }],
        begin_date: [
          { required: true, message: "请输入开始时间", trigger: "blur" },
        ],
        end_date: [
          { required: true, message: "请输入结束时间", trigger: "blur" },
        ],
        choice_name: [
          { required: true, message: "请输入投票选项", trigger: "blur" },
        ],
      },
      title: "投票",
      dialogType: "new",
      dialogVisible: false,

      datas: [],
      current_row: null,

      selections: [],
      itemSels: [],
      listLoading: true,
      listQuery: {
        name: null,
        page: 1,
        page_size: 15,
      },
      total: 0,
      ///图片上传
      uploadForm: {
        choice_name: "",
        choice_id: null,
        images: [],
      },
      fileList: [],
      dlgUploadVisible: false,
      dlgImageVisible: false,
      dlgImageUrl: "",
      choice_id: null,

      tableColumns: [
        {
          key: "name",
          title: "投票题目",
          align: "left",
          width: "400",
        },
        {
          key: "begin_date",
          title: "开始时间",
          width: "110",
        },
        {
          key: "end_date",
          title: "结束时间",
          width: "110",
        },
        {
          key: "cate_name",
          title: "类型",
          width: "80",
        },
        {
          key: "max_num",
          title: "最大数量",
          width: "80",
        },
        {
          key: "flag_name",
          title: "状态",
          width: "80",
        },
        {
          key: "desc",
          title: "说明",
          align: "left",
        },
      ],
      flags: [
        { value: 0, label: "无效" },
        { value: 1, label: "有效" },
      ],

      cates: [
        { value: 0, label: "图文" },
        { value: 1, label: "文字" },
      ],
      pickerOptions,
    };
  },
  components: {
    Pagination,
  },
  computed: {
    ...mapGetters(["uid", "token"]),
    getTitle() {
      return this.dialogType == "new"
        ? `新增${this.title}`
        : `修改${this.title}`;
    },
    headerObj() {
      return {
        authorization: "JWT " + this.token,
      };
    },
    uploadData() {
      return {
        choice_id: this.choice_id,
      };
    },
  },
  created() {
    this.getQuestionList();
  },

  methods: {
    getQuestionList() {
      this.listLoading = true;

      getQuestions(this.listQuery)
        .then((res) => {
          this.datas = res.results;
          this.total = res.count;
          this.listLoading = false;
        })
        .catch((err) => {
          this.listLoading = false;
          this.$message.error("获取数据失败!");
        });
    },

    // 查询
    handleFilter() {
      this.listQuery.page = 1;

      this.getQuestionList();
    },

    //添加
    handleAdd() {
      this.dialogVisible = true;

      this.dialogType = "new";

      this.form.choices = [];

      this.form = Object.assign({}, defaultForm);

      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },

    //修改
    handleEdit(scope) {
      this.dialogType = "edit";
      this.current_row = scope.row;
      this.form = JSON.parse(JSON.stringify(scope.row));
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },

    ///上传图片
    handleUpload(row) {
      this.fileList = [];
      this.dlgUploadVisible = true;
      this.uploadForm.choice_id = row.id;
      this.uploadForm.choice_name = row.name;
      this.uploadForm.images = row.images;
      this.choice_id = row.id;
      this.fileList = row.images.map((item) => {
              return {
                name: "",
                url: item.image,
                id: item.id,
              };
            });
    },

    //上传前
    handleBeforeUpload(file) {
      const flag = file.size / 1024 / 1024 < 5;
      if (!flag) {
        this.$message.error("上传文件大小不能超过 5MB!");
      }
      return flag;
    },
    // 预览
    handlePreview(file) {
      this.dlgImageUrl = file.url;
      this.dlgImageVisible = true;
    },

    handleSuccess(res, file, filelist) {
      this.fileList = filelist;
      if (res.status_code == 200) {
        this.uploadForm.images.push(file.response.file);
        this.$message.success("图片上传成功");
      } else {
        this.$message.error("上传失败");
      }
    },

    handleClose() {
      this.fileList = [];
    },

    //图片删除
    handleRemove(file, fileList) {
      this.fileList = fileList;
      var file_id = null;
      file_id = file.id;
      if (file_id == null) {
        if (file.response.status_code == 200) {
          file_id = file.response.file.id;
        }
      }

      if (file_id == null) return;

      delChoiceImage(file_id)
        .then((res) => {
          const index = this.uploadForm.images.findIndex(
            (item) => item.id == file_id
          );
          if (index > -1) {
            this.uploadForm.images.splice(index, 1);
          }
          this.$message.success("删除成功");
        })
        .catch((error) => {
          this.$message.error("删除失败");
        });
    },

    //确定添加数据
    async handleSave(flag) {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        let res = null;
        if (this.dialogType == "new") {
          console.log(this.form);
          try {
            res = await addQuestion(this.form);
          } catch (err) {
            this.$message.error("增加失败!");
          }
        } else {
          try {
            res = await updateQuestion(this.form);
          } catch (err) {
            // console.log(err);
            this.$message.error("修改失败!");
          }
        }

        this.dialogVisible = false;
        this.getQuestionList();

        const { name, begin_date, end_date } = res;

        if (flag) {
          this.form = Object.assign({}, defaultForm);
          this.dialogType = "new";
        } else {
          this.dialogVisible = false;
        }

        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>投票题目: ${name}</div>
              <div>开始时间: ${begin_date}</div>
              <div>结束时间: ${end_date}</div>
            `,
          type: "success",
        });
      });
    },
    //弹窗显示，数据回显

    //删除数据
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delQuestion(row.id);

          this.getQuestionList();

          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },

    handleBatchDelete() {
      if (this.selections.length == 0) {
        this.$message.warning("请选择要删除记录");
        return;
      }
      this.$confirm("确定要删除选中记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const sel_ids = {
            select_ids: this.selections,
          };
          const res = await delQuestions(sel_ids);
          this.getQuestionList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },

    handleSelectionChange(val) {
      this.selections = val.map((item) => item.id);
    },

    handleItemChange(val) {
      this.itemSels = val;
    },

    addItem() {
      let itemForm = Object.assign({}, defChoiceItem);
      this.form.choices.push(itemForm);
    },

    //批量删除
    deleteItem() {
      if (this.itemSels.length == 0) {
        this.$message.warning("请选择要删除记录");
        return;
      }

      this.$confirm("确定要删除选中记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const sel_ids = {
            select_ids: this.itemSels
              .filter((item) => {
                return item.id != undefined;
              })
              .map((item) => item.id),
          };

          if (sel_ids.select_ids.length > 0) {
            const res = await delChoices(sel_ids);
          }

          this.form.choices = this.form.choices.filter((item) => {
            return !this.itemSels.includes(item);
          });

          if (this.current_row != null) {
            this.current_row.choices = this.current_row.choices.filter(
              (item) => {
                return !this.itemSels.includes(item);
              }
            );
          }

          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          this.$message({
            type: "error",
            message: "删除失败!" + err,
          });
        });
    },
  },
};
</script>

<style scoped>
</style>